package main

import (
	"db2s/Store"
	"db2s/arg"
	"db2s/linces"
	"db2s/plparse"
	_switch "db2s/switch"
	"fmt"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"
	"reflect"
	"strings"
	"time"
)

func funcCheck(m arg.ConfigParameter) {
	if _, ok := _switch.ModeFunc[_switch.GetModeName(m.SecondaryL.FunctionalMode)]; !ok {
		fmt.Println(fmt.Sprintf("-- %v report: Input module error! curry mode is {%v} What is expected {%v}", arg.ToolName, m.SecondaryL.FunctionalMode,
			func() string {
				p := arg.GetDbPoolCheck()
				return strings.Join(p.FunctionalMode, ",")
			}()))
	}
	funcName, _ := _switch.ModeFunc[_switch.GetModeName(m.SecondaryL.FunctionalMode)]
	if funcName.Kind() == reflect.Func {
		args := []reflect.Value{
			reflect.ValueOf(m),
		}
		funcName.Call(args)
	}
}

// 启动 HTTP 服务器
func startHTTPServer() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, this is a simple HTTP server running as a daemon!")
	})
	fmt.Println(fmt.Sprintf("Starting HTTP server on port 8080..."))
	go func() {
		if err := http.ListenAndServe(":8989", nil); err != nil {
			fmt.Println(fmt.Sprintf("Failed to start HTTP server: %v", err))
		}
	}()
}

// 启动 TCP 服务器
func startTCPServer() {
	listener, err := net.Listen("tcp", ":9090")
	if err != nil {
		fmt.Println(fmt.Sprintf("Failed to start TCP server: %v", err))
	}
	defer listener.Close()

	fmt.Println(fmt.Sprintf("Starting TCP server on port 9090..."))
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println(fmt.Sprintf("Failed to accept connection: %v", err))
			continue
		}
		go handleTCPConnection(conn)
	}
}

// 处理 TCP 连接
func handleTCPConnection(conn net.Conn) {
	defer conn.Close()
	fmt.Println(fmt.Sprintf("Accepted TCP connection"))
	_, err := conn.Write([]byte("Hello from TCP server!\n"))
	if err != nil {
		fmt.Println(fmt.Sprintf("Failed to write to connection: %v", err))
	}
}
func auth() {
	fmt.Println("---authCode:", linces.GenerateAuthCode("ce5117a5069e007ae1f460e2aac45e2496f2a9b06dc060209d1dc71723ac413d", linces.AesKey))
}

func bb() {
	sql := `SELECT manager_id, last_name, hire_date, salary,
            AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date
            ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS c_mavg
            FROM employees
            ORDER BY manager_id, hire_date, salary;`
	plparse.Parse(strings.ToUpper(sql))
}

func main() {
	//获取当前时间
	beginTime := time.Now()
	//获取配置文件
	m, err := arg.ConfigInit(0)
	if err != nil {
		fmt.Println(fmt.Sprintf("%v report: %v", arg.ToolName, err))
		os.Exit(1)
	}
	//bb()
	m.BeginTime = beginTime
	if err = Store.Init(); err != nil {
		fmt.Println("--------QQQ:", err)
		return
	}
	funcCheck(m)
	//auth()
}
